<template>
  <main class="p-2 flex flex-col justify-center items-center text-3xl">
    <h1 class="py-5">加减法</h1>
    <div class="flex flex-row justify-center items-center mb-5 gap-2">
      <label for="input_number">
        No:
        <input type="number" id="input_number" min="1" max="99" v-model="no" class="h-12 w-24 text-center" />
      </label>
      <label for="input_min">
        Min:
        <input type="number" id="input_min" v-model="min" min="1" class="h-12 w-24 text-center" />
      </label>
      <label for="input_max">
        Max:
        <input type="number" id="input_max" v-model="max" class="h-12 w-24 text-center" />
      </label>
      <label for="">
        <Button type="button" @click="onGen" label="生成" rounded class="w-20"></Button>
      </label>
    </div>

    <div class="grid sm:grid-cols-3 lg:grid-cols-4 gap-5 mb-8">
      <div class="flex justify-end items-center" v-for="(q, index) in questions" :key="index">
        <span class="mr-2"> {{ q.problem + ' = ' }} </span>
        <input
          type="number"
          class="h-14 rounded-lg w-20 float-right text-center border-2"
          :class="{ 'border-red-500': done && q.answer != q.reply, 'border-green-500': done && q.answer == q.reply }"
          v-model="q.reply"
        />
      </div>
    </div>
    <Button :disabled="disable" type="button" @click="onDone()" label="交卷" rounded class="mt-8 w-1/2" />
  </main>
</template>
<script setup>
  import { ref, watchEffect } from 'vue';

  const no = ref(20);
  const min = ref(1);
  const max = ref(20);
  const questions = ref([]);
  const done = ref(false);
  const disable = ref(true);

  function generateRandomNumber() {
    return Math.floor(Math.random() * max.value) + 1;
  }

  function generateRangeRandomNumber() {
    return Math.floor(Math.random() * (max.value - min.value + 1)) + min.value;
  }

  function generateProblem() {
    // let [num1,num2] = [generateRandomNumber(),generateRandomNumber()];

    let [num1, num2] = [generateRangeRandomNumber(), generateRangeRandomNumber()];

    const operator = Math.random() < 0.5 ? '+' : '-';

    [num1, num2] = num1 < num2 ? [num2, num1] : [num1, num2];

    const problem = `${num1} ${operator} ${num2}`;
    const answer = operator === '+' ? num1 + num2 : num1 - num2;
    return { problem, answer, reply: '' };
  }

  watchEffect(() => {
    disable.value = !!questions.value.find(q => q.reply === '');
  });

  function onGen() {
    done.value = false;
    questions.value = [];
    for (let i = 0; i < no.value; i++) {
      questions.value.push(generateProblem());
    }
  }

  onGen();

  function onDone() {
    done.value = true;
  }
</script>

<style scoped>
  .diy .p-inputnumber-input {
    width: 1rem;
    font-size: 1rem;
    padding: 0;
  }
</style>
